package org.example.utils.doc;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
import org.example.entity.ParseDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class DocUtils {
    private static final Logger log = LoggerFactory.getLogger(DocUtils.class);

    public static ParseDocument recognize(String filePath) {
        log.info("Starting to parse document: {}", filePath);

        log.info("Starting to parse document: {}", filePath);

        // 检查文件是否存在
        File file = new File(filePath);
        if (!file.exists()) {
            log.error("File does not exist: {}", filePath);
            throw new DocumentParsingException("File not found: " + filePath, new Exception("File not found"));
        }

        // 检查是否为空文件
        if (file.length() == 0) {
            log.warn("File is empty: {}", filePath);
            throw new DocumentParsingException("File is empty" + filePath, new Exception("File is empty"));
        }


        AutoDetectParser parser = new AutoDetectParser();
        BodyContentHandler handler = new BodyContentHandler(-1); // -1 表示无长度限制
        Metadata metadata = new Metadata();
        ParseContext context = new ParseContext();

        try (InputStream stream = new FileInputStream(filePath)) {
            parser.parse(stream, handler, metadata, context);
        } catch (IOException | TikaException | SAXException e) {
            log.error("Failed to parse document: {}", filePath, e);
            throw new DocumentParsingException("Document parsing failed: " + filePath, e);
        }

        ParseDocument result = new ParseDocument();
        result.setContent(handler.toString());
        result.setType(metadata.get(Metadata.CONTENT_TYPE));
        result.setAuthor(metadata.get("Author"));
        result.setTitle(metadata.get("title"));

        log.debug("Successfully parsed document, content length: {}", result.getContent().length());
        return result;
    }
}
